package com.balloon.gateway.security.handler;

import com.balloon.gateway.comm.ResultVO;
import com.balloon.gateway.comm.ResultVOUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;

/**
 * @author liaofuxing
 * @version 1.0.0
 * @date 2022/3/8 11:12
 * @description 拒绝访问返回处理器
 */
@Component
public class DefaultAccessDeniedHandler implements ServerAccessDeniedHandler {
    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, AccessDeniedException denied) {
        return Mono.defer(() -> Mono.just(exchange.getResponse()))
                .flatMap(response -> {
                    response.setStatusCode(HttpStatus.OK);
                    response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
                    DataBufferFactory dataBufferFactory = response.bufferFactory();
                    ResultVO<String> resultVO = ResultVOUtils.credentials_expired("");
                    try {
                        String json = objectMapper.writeValueAsString(resultVO);
                        DataBuffer buffer = dataBufferFactory.wrap(json.getBytes(
                                Charset.defaultCharset()));
                        return response.writeWith(Mono.just(buffer));
                    } catch (JsonProcessingException e) {
                        e.printStackTrace();
                    }
                    return Mono.error(new Exception());
                });
    }
}